PreferenceScreen에 버튼을 추가하는 방법
기본 설정 화면 하단에 버튼을 추가하고 스크롤 할 때 올바르게 작동하도록하는 방법이 있습니까?
기본 설정의 모양을 사용자 지정하는 또 다른 솔루션이 있습니다.
단추 또는 표준 환경 설정에 추가 할 항목이있는 일반 XML 레이아웃을 디자인하십시오. ListView
레이아웃에를 포함 하고 ID를 제공합니다 @android:id/list
.
레이아웃 파일을라고합시다 res/layout/main.xml
. 다음과 같이 보일 수 있습니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button android:text="This is a button on top of all preferences."
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
에서 PreferenceActivity
다음 두 줄을 추가하십시오 onCreate
.
addPreferencesFromResource(R.xml.preferences);
setContentView(R.layout.main);
그러면 ListView
레이아웃의가에서 일반적인 방식으로 정의 된 기본 설정으로 대체됩니다 res/xml/preferences.xml
.
나는 이것이 조금 늦었다는 것을 알고 있지만 Max의 칭찬하는 솔루션보다 더 좋아하는 솔루션을 찾았습니다.
다음과 같이 PreferenceActivity의 ListView에 바닥 글 (또는 단추가 맨 위에있는 경우 머리글)을 간단히 추가 할 수 있습니다.
public class MyActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListView v = getListView();
v.addFooterView(new Button(this));
}
}
누군가에게 도움이되기를 바랍니다.
아래의 예제는 페이지 하단에 버튼을 렌더링합니다 (아직 관심이있는 사람이있는 경우).
LinearLayout의 경우 가중치를 적용 할 수도 있습니다. 이것은 Listview가 * fill_parent *로 설정되어 있기 때문에 필요합니다. 나는 일반적으로 * android : layout_weight *를 추가하여 이것을 수행합니다.
<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="fill_parent"
android:layout_height="fill_parent" android:layout_weight="10"/>
<Button android:text="This is a button on top of all preferences."
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="1"/>
</LinearLayout>
아래 설명은 100 %는 아니지만 이해하는 데 도움이 될 것입니다.
+-- View Port (linear layout)
| +-- List View (this is where the preferences will go)
| |
| |
| +--
+--
+--
| Button (which was pushed out of view by the fillparent of ListView
+--
버튼에 무게가 없기 때문에 말할 수도 있습니다. 버튼은 0dp 높이로 렌더링됩니다.
이제 layout_weigths가 추가되면 버튼이 표시됩니다.
+-- View Port (linear layout)
| +-- List View (this is where the preferences will go)
| |
| |
| +--
| +--
| | Button (which was pushed out of view by the fillparent of ListView
| +--
+--
사실 해결책이 있습니다. 여기에 코드가 있습니다. 이것은 누구에게나 유용 할 것입니다. 화면 해상도와 관계없이 화면 하단에 3 개의 옵션과 2 개의 버튼이있는 것처럼 보입니다 (가장 낮은 값으로 240을 타겟팅).
package com.myapplication.gui;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.view.Display;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import com.myproject.general.HeightListView;
import com.myapplication.R;
public class FilterActivity extends PreferenceActivity {
private LinearLayout rootView;
private LinearLayout buttonView;
private Button buttonDone;
private Button buttonRevert;
private ListView preferenceView;
private LinearLayout gradientView;
private ScrollView scrollRoot;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int height = display.getHeight();
int width = height > 240 ? display.getWidth() : display.getWidth() - 4;
scrollRoot = new ScrollView(this);
scrollRoot.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
rootView = new LinearLayout(this);
rootView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
rootView.setOrientation(LinearLayout.VERTICAL);
buttonView = new LinearLayout(this);
buttonView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
buttonView.setOrientation(LinearLayout.HORIZONTAL);
buttonView.setGravity(Gravity.BOTTOM);
gradientView = new LinearLayout(this);
gradientView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
gradientView.setOrientation(LinearLayout.HORIZONTAL);
gradientView.setBackgroundResource(R.drawable.gradient);
gradientView.setPadding(0, 5, 0, 0);
gradientView.setBackgroundResource(R.drawable.gradient);
buttonDone = new Button(this);
buttonDone.setText(R.string.filterButton_Done);
buttonDone.setLayoutParams(new LayoutParams(width/2, LayoutParams.WRAP_CONTENT));
gradientView.addView(buttonDone);
buttonRevert = new Button(this);
buttonRevert.setText(R.string.filterButton_Revert);
buttonRevert.setLayoutParams(new LayoutParams(width/2, LayoutParams.WRAP_CONTENT));
gradientView.addView(buttonRevert);
buttonView.addView(gradientView);
preferenceView = new HeightListView(this);
preferenceView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
preferenceView.setId(android.R.id.list);
PreferenceScreen screen = createPreferenceHierarchy();
screen.bind(preferenceView);
preferenceView.setAdapter(screen.getRootAdapter());
rootView.addView(preferenceView);
rootView.addView(buttonView);
if (height > 240) {
this.setContentView(rootView);
}
else {
scrollRoot.addView(rootView);
this.setContentView(scrollRoot);
}
setPreferenceScreen(screen);
}
private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
PreferenceScreen pref1 = getPreferenceManager().createPreferenceScreen(this);
pref1.setKey("pref1");
pref1.setTitle("Title");
pref1.setSummary("Summary");
root.addPreference(pref1);
PreferenceScreen pref2 = getPreferenceManager().createPreferenceScreen(this);
pref2.setKey("pref2");
pref2.setTitle("Title");
pref2.setSummary("Summary");
root.addPreference(pref2);
PreferenceScreen pref3 = getPreferenceManager().createPreferenceScreen(this);
pref3.setKey("pref3");
pref3.setTitle("Title");
pref3.setSummary("Summary");
root.addPreference(pref3);
return root;
}
}
일반 활동 내에서 PreferenceFragment를 사용하고 활동 레이아웃에 버튼을 추가하기 만하면됩니다.
public class SettingActivity extends Activity {
UserProfileViewModel userProfileViewModel = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
getFragmentManager().beginTransaction()
.replace(R.id.content, new SettingsFragment())
.commit();
}
private class SettingsFragment extends PreferenceFragment {
public SettingsFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.pref_main);
}
}
}
SettingActivity.java
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/buttonSave"/>
<Button
android:id="@+id/buttonSave"
android:text="Save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
activity_setting
이것은 ronny의 예제 활동에서 코드가 어떻게 보이는지입니다. 내 의도는 화면 하단에 메뉴를 배치하는 것이 었습니다.
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prefs);
addPreferencesFromResource(R.xml.prefs);
/* LayoutInflater CX = getLayoutInflater();
CX.inflate(R.layout.main,null);*/
// TODO Auto-generated method stub
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="@dimens/listview_height" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="This is a button on top of all preferences." />
</RelativeLayout>
@Ronnie를 참조하고 RelativeLayout을 사용하고 listview의 layout_height에 대한 높이를 설정 한 다음 버튼의 layout_alignParentBottom = "true"를 설정합니다. PreferenceScreen 하단에 버튼을 렌더링 할 수 있습니다. 그런 다음 @Max의 방법을 사용하십시오. 내 필요에 맞게 작동합니다.
안드로이드 표준 접근 방식을 위해 액션 바에 액션 버튼을 추가하는 것도 가능합니다.
public class PrefActivity extends PreferenceActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.preference_header_menu, menu);
return super.onCreateOptionsMenu(menu);
}
}
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_add"
android:icon="@drawable/ic_menu_add_dark"
android:title="@string/menu_action_add_title"
android:showAsAction="always" />
</menu>
Preference Activity의 사용자 정의보기는 Android의 PreferenceActivity에 사용자 정의보기를 추가하는 데 도움이됩니다.
main.xml을 작성하십시오. 필요한 유일한보기는 ID가있는 ListView android:id="@android:id/list"
입니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:weightSum="1">
<ListView
android:id="@android:id/list"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="0dp">
</ListView>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
CustomPreferenceActivity.java 생성
public class CustomPreferenceActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addPreferencesFromResource(R.xml.settings);
//setup any other views that you have
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("View Added");
}
}
다음은 기본 설정 화면에 클릭 가능한 버튼을 추가하는 간단한 솔루션입니다. 환경 설정이 이미 android : widgetLayout에 공간을 예약하고 버튼이 android : onClick을 사용하여 클릭을 전달할 수 있기 때문에 이것은 쉽습니다.
먼저 콘텐츠로 button.xml을 만듭니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="BUTTON"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:onClick="onButtonClick"/>
</LinearLayout>
이제 preferences.xml에서 환경 설정을 추가하십시오.
<Preference
android:key="button"
android:title="Title"
android:summary="Summary"
android:widgetLayout="@layout/button" />
이제 PreferenceActivity는 onButtonClick 멤버 만 포함하면됩니다.
public class MainActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.main_preferences);
}
public void onButtonClick(View v) {
Log.d("Button", "Yeah, button was clicked");
}
}
preferences.xml :
<Preference
android:key="clearAllData"
android:title="@string/settings_clear_all_data">
</Preference>
SettingsFragment.java :
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
Preference clearAllData = (Preference) findPreference("clearAllData");
// setup buttons
final Context context = getActivity();
clearAllData.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
...
}
}
}
PreferenceScreen
사용자 지정 레이아웃 내부 의 컨테이너 를 '포장'하기 위해 만든 레이아웃 (그런 다음 아래에 버튼을 추가 ListView
)이 실제로 작동하지 않았기 때문에 위의 모든 답변을 사용할 수 없음을 발견했습니다.
그들은 기본 설정 목록 위에 사용자 지정 레이아웃을 오버레이 (플로팅)하고 새 사용자 지정 버튼을 클릭 (예 : 새 사용자 지정 버튼)하면 버튼 아래의 기본 설정 만 호출됩니다.
그러나을 사용할 때 환경 설정 목록 컨테이너 아래에 버튼을 추가하는 데 도움 이 되는 이 솔루션 을 찾았습니다 PreferenceFragment
.
참고 URL : https://stackoverflow.com/questions/2697233/how-to-add-a-button-to-preferencescreen
'Programming' 카테고리의 다른 글
사전과 해시 테이블의 차이점 (0) | 2020.08.08 |
---|---|
정의되지 않은 매크로 : AC_MSG_ERROR (0) | 2020.08.08 |
Spring-Data-JPA 주석에 대한 setMaxResults? (0) | 2020.08.08 |
RecyclerView는 "스크래핑되거나 연결된 뷰가 재활용되지 않을 수 있습니다." (0) | 2020.08.08 |
노드 영구 / usr / bin / env : node : 해당 파일 또는 디렉토리 없음 (0) | 2020.08.08 |