Search code examples
androidviewclickable

Set up android view clickable


I set up splash activity which start another activity after few second. Anyway I wanted to add one more capability: to start the second activity not only after 5 second but after a click on my splash view. As soon as I set up the next:

View v = (View)findViewById(R.layout.splash); 
    v.setOnClickListener(this);
    setContentView(v);

instead of

setContentView(R.layout.splash);

my project does not run. Where is the problem?

Here is my code:

public class SlashC extends Activity implements Runnable, OnClickListener {
Thread timer;
MediaPlayer hTree;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View v = (View)findViewById(R.layout.splash); // problems start here
    v.setOnClickListener(this);
    setContentView(v);

    hTree = MediaPlayer.create(this, R.raw.happy_tree);
    hTree.start();
    timer = new Thread(this);
    timer.start();

}
public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent class2 = new Intent("com.roger.calc.MainActivity");
    startActivity(class2);
}
public void run() {
    // TODO Auto-generated method stub
    try {
        timer.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        Intent class2 = new Intent("com.roger.calc.MainActivity");
        startActivity(class2);
    }       
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    hTree.release();
    finish();
}}

And XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/splash2"
android:clickable="true" >
</LinearLayout>

Solution

  • Make the LinearLayout clickable by setting layout attribute android:clickable="true", android:focusable="true" and android:focusableInTouchMode="true" from xml or setClickable(true) from code. set onClickListener as

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/splash"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusableInTouchMode="true"
        android:clickable="true"
        android:focusable="true" 
        android:orientation="vertical"
        android:background="@drawable/splash2"/>
    

    and in code part:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        ((LinearLayout)findViewById(R.id.splash)).setOnClickListener(this);
    
        /// YOUR CODE HERE