louis louis - 3 months ago 8
Android Question

why android onlick in main activity not working

i build a new android app with empty activity
and added a onlick functionality just for testing but
something seems to not working

the app runs on my LGg2 android devive
but it seems that the onclick listener does not response
when i click at the button(id:butt)

in debug mode i can step and see the listener is build
but i never come to the breakpoint
in the line where i set the text (.. t.setText(...

Can someone see , what im doing wrong ?

here is my Layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.admin.test.MainActivity">

<TextView
android:id="@+id/t"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<Button
android:id="@+id/butt"
android:layout_below="@+id/t"
android:text="assdasd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"

/>
</RelativeLayout>


and here the mainactivity where i have the onclicklistener

public class MainActivity extends AppCompatActivity
{
public static View rootView;

public static Button b;
public static TextView t;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

rootView = getLayoutInflater().inflate(R.layout.activity_main, null);
b = (Button) rootView.findViewById(R.id.butt);
t = (TextView) rootView.findViewById(R.id.t);
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
t.setText("lsdallsd");
Log.d("asadssd","ssdasd");
view.setBackgroundColor(Color.RED);

}
});
}
}

Answer

instead of

rootView = getLayoutInflater().inflate(R.layout.activity_main, null);
b = (Button) rootView.findViewById(R.id.butt);
t = (TextView) rootView.findViewById(R.id.t);

use

b = (Button)findViewById(R.id.butt);
t = (TextView) findViewById(R.id.t);