In Android Studio why is there no TextViewPreference?

Tags: , ,



Ok so I wanted to create a Settings activity. I was told using the Preference layout makes it much easier. I want a TextView that when clicked does a certain action, yet there is no TextViewPreference. The closest thing is EditTextPreference that must have the attribute “selectable” set to off which turns it gray.

Also another thing, these Preferences have no ID attribute. How am I supposed to attach OnClickListeners to them if they have no ID???

Answer

try–>

Method 1

create a custom preference layout item and use it in the Preference Activity:-

<?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="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:paddingRight="?android:attr/scrollbarSize">

    <TextView android:id="@android:id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal" />

  </LinearLayout>

add in preference xml:

<Preference
android:title="@string/label_pref_version"
android:key="@string/pref_version"
android:layout="@layout/pref" />

then lastly:-

fire findViewById in your Activity code and attach a listener….

Method 2

For the xml:

<Preference android:title="Acts like a text"
            android:key="@string/myCooltext"
            android:summary="This is a text"/>

Then for the java in your onCreate()

Preference text = findPreference(getString(R.string.myCoolText));
text.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {   
                //code for what you want it to do   
                return true;
            }
        });

Method 3

You can try it like this to get the Textview in activity:

 View name= ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layouttext, null, false);

add android:id to the LinearLayout that contains the Textview in layouttext.xml, i.e. android:id=”@+id/mylayout”

 LinearLayout mLayout = (LinearLayout)name.findViewById(R.id.mylayout);
  Textview login = (Textview) footerView.findViewById(R.id.Text);
  login.setOnClickListener(this);


Source: stackoverflow