我設計了一個應用程序,我使用Tabhost,並添加了兩個選項卡。當「長按」此選項卡時,我想重命名標籤Device1
。我嘗試某種方式,但它不工作。我已經實現如下:如何重命名選項卡android使用tabhost和長時間點擊
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabHost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<HorizontalScrollView
android:id="@+id/horScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="none" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</HorizontalScrollView>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/Device1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingTop="80px" >
</LinearLayout>
<LinearLayout
android:id="@+id/Device2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingTop="80px" >
</LinearLayout>
</FrameLayout>
MainActivity.java
package com.example.renametab;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;
public class MainActivity extends Activity {
public static TabHost tabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabSpec tabDevice1 = tabHost.newTabSpec("Device1");
tabDevice1.setContent(R.id.Device1);
tabDevice1.setIndicator("Device1");
TabSpec tabDevice2 = tabHost.newTabSpec("Device2");
tabDevice2.setContent(R.id.Device2);
tabDevice2.setIndicator("Device2");
tabHost.addTab(tabDevice1);
tabHost.addTab(tabDevice2);
tabHost.getTabWidget().getChildAt(0).setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
//How to rename tab????
//I try this way but it is false
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(0).findViewById(R.id.Device1);
tv.setText("New Name Tab");
return true;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
你能解釋一下當我有n個選項卡並且選項卡數量動態變化時ally –
您可以像'int numTabs = mTabHost.getTabWidget()。getTabCount();'然後使用for循環來獲取每個選項卡,找到其標題文本,並設置其長時間點擊偵聽器。 –