This is my first time to use PreferenceActivity
.
I have made a simple activity for a settings screen, and when I set up a button in the layout and set the onClickListener
for the button, there are no actions nor are there any errors.
All I want to do is to send the user back to the main screen by pressing the button. Is there some error or some setup that I have missed?
The mysterious part is that neither the xml onClick
nor the direct method call work. No actions, no errors, it does not even show a Toast
(when altered for debugging). Is there anyone who actually used PreferenceActivity
and used some widgets like buttons ?
Here is my sample activity for the Settings Screen
public class Settings extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//This button doesn't work
Button b = (Button)findViewById(R.id.setupid);
b.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent i = new Intent(Settings.this,HomeActivity.class);
startActivity(i);
}
});
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
}
Here is the xml layout for the Settings.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<ListView android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3498db"
android:gravity="center"
>
<Button
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="Set"
android:id="@+id/setupid" />
</LinearLayout>
</LinearLayout>
You didn't have to use the Fragment in the first place. All you have to do is to use addPreferencesFromResource(R.xml.preferences); under setContents View.
public class Settings extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//It is depricated but it works
addPreferencesFromResource(R.xml.preferences);
Button b = (Button)findViewById(R.id.setupid);
b.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent i = new Intent(Settings.this,HomeActivity.class);
startActivity(i);
}
});
//getFragmentManager().beginTransaction().replace(android.R.id.content, //new MyPreferenceFragment()).commit();
}
}