我有问题但我无法完成。我有MainActivity,其中包含带有片段的幻灯片菜单。启动应用程序HomeFragment在窗口中设置。在Home Fragment中我有处理程序从蓝牙服务获取消息。此处理程序更改了Home Fragment中的文本视图来自"您未连接" - > "连接..." - > "你已经连接了#34;。启动应用程序后它完美运行。但是当我从幻灯片菜单中选择另一个片段并返回到Home Fragment时,文本视图没有显示出来。在LogCat中,一切看起来都很好 - TextView.getText()返回正确的文本。但它没有显示 - TextView字段为空。下面我将向您展示MainActivity和HomeFragment类+ HomeFragment xml。我试过runOnUiThread,handler.post,什么都没有...
package io.panwrona.cheaproomduino;
public class MainActivity extends ActionBarActivity{
private static final String CLASS_TAG = "MainActivity";
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private List<String> sceneryTypeList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initFragment(new HomeFragment());
//
// if(savedInstanceState == null){
//
// }
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6,-1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* A placeholder fragment containing a simple view.
*/
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public void onRestart(){
super.onRestart();
Log.d(CLASS_TAG, CLASS_TAG + " Restarted");
}
@Override
public void onResume(){
super.onResume();
Log.d(CLASS_TAG, CLASS_TAG + " Resumed");
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new DevicesFragment();
break;
case 2:
// i = new Intent(this, SceneryActivity.class);
// startActivity(i);
break;
case 3:
// i = new Intent(this, SceneryActivity.class);
// startActivity(i);
break;
case 4:
// i = new Intent(this, SceneryActivity.class);
// startActivity(i);
break;
case 5:
// i = new Intent(this, SceneryActivity.class);
// startActivity(i);
break;
case 6:
// i = new Intent(this, SceneryActivity.class);
// startActivity(i);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
// menu.findItem(R.id.bluetooh_options_devices).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
@Override
public void onDestroy(){
super.onDestroy();
Log.d(CLASS_TAG, CLASS_TAG + " Destroyed!");
}
@Override
public void onPause(){
super.onPause();
Log.d(CLASS_TAG, CLASS_TAG + " Paused!");
}
@Override
public void onStop(){
super.onStop();
Log.d(CLASS_TAG, CLASS_TAG + " Stopped!");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.string.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
package io.panwrona.cheaproomduino;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import io.panwrona.cheaproomduino.connection.BluetoothConnectionService;
import io.panwrona.cheaproomduino.connection.DevicesList;
import io.panwrona.cheaproomduino.database.DatabaseHelper;
import io.panwrona.cheaproomduino.database.TinyDB;
import io.panwrona.cheaproomduino.database.database_models.BluetoothDeviceModel;
public class HomeFragment extends Fragment {
private static final String CLASS_TAG = "HomeFragment";
// Handlers 'cases'
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
//
// // Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private String connectedDeviceName = null;
private String connectedDeviceAddress = null;
Context context;
private Button connectButton;
private TextView connectTxt;
BluetoothAdapter btAdapter;
public BluetoothConnectionService btService = null;
BluetoothDevice btDevice = null;
DatabaseHelper db;
TinyDB tinyDB;
// public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(CLASS_TAG + "/" + "onCreateView", "in onCreateView");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
if(connectButton == null){
connectButton = (Button)rootView.findViewById(R.id.main_connect_button);
connectButton.setOnClickListener(new ConnectionClickListener());
}
if(connectTxt == null){
connectTxt = (TextView)rootView.findViewById(R.id.try_txt);
}
if(tinyDB != null){
mHandler.sendEmptyMessage(tinyDB.getInt("connection_state"));
}
if(btService != null && btService.getCurrentState() == 2){
connectTxt.setText(tinyDB.getString("connected_device"));
connectButton.setText(tinyDB.getString("connected_device_btn"));
}
return rootView;
}
private int msgWhat;
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
if(context == null){
context = getActivity().getApplicationContext();
}
btAdapter = BluetoothAdapter.getDefaultAdapter();
db = new DatabaseHelper(context);
tinyDB = new TinyDB(context);
if(((cBaseApplication)context).getBtService() == null){
btService = ((cBaseApplication)context).getBtService(mHandler);
}else{
btService = ((cBaseApplication)context).getBtService();
}
checkBluetoothState();
try{
Log.d("HomeFragment", "State: " + btService.getCurrentState());
String test = "Test";
byte[] testByte = test.getBytes();
btService.write(testByte);
} catch(NullPointerException e){
e.printStackTrace();
}
btService.getState();
if(true){
connectTxt.setVisibility(View.VISIBLE);
}
}
@Override
public void onAttach(Activity a){
super.onAttach(a);
Log.d(CLASS_TAG, "in onAttach() !");
if(a == null){
Log.d(CLASS_TAG, "in onAttach() ! Activity: null");
} else {
Log.d(CLASS_TAG, "in onAttach() ! Activity: " + a);
}
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(true) Log.i(CLASS_TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothConnectionService.STATE_CONNECTED:
List<BluetoothDeviceModel> btModels = db.getBluetoothDevicesList();
boolean btModelExist = false;
for(BluetoothDeviceModel model : btModels){
if(model.getBluetoothDeviceName().equals(connectedDeviceName)){
btModelExist = true;
}else{
btModelExist = false;
}
}
if(btModelExist != false){
BluetoothDeviceModel model =
new BluetoothDeviceModel(connectedDeviceName,
connectedDeviceAddress);
Log.d(CLASS_TAG + "BLUETOOTHDEVICEMODEL", "Bt Device Model: "
+ connectedDeviceName + " " + connectedDeviceAddress);
new AlertBox("Saving bluetooth device...",
"Do you want to save this device: "
+ connectedDeviceName + " ?",
model,
getActivity());
}
tinyDB.putString("connected_device","Connected to: "
+ connectedDeviceName);
tinyDB.putString("connected_device_btn",
"Disconnect");
//Log.d(CLASS_TAG + "/" + "Handler", "In State Connected runnable");
connectTxt.setText("Connected to: " + connectedDeviceName);
connectButton.setText("Disconnect");
tinyDB.putInt("connection_state",
BluetoothConnectionService.STATE_CONNECTED);
break;
case BluetoothConnectionService.STATE_CONNECTING:
connectTxt.setText("Connecting...");
break;
case BluetoothConnectionService.STATE_NONE:
tinyDB.putInt("connection_state",
BluetoothConnectionService.STATE_NONE);
connectButton.setText("Connect");
connectTxt.setText("You're not connectedd");
Log.d(CLASS_TAG, connectTxt.getText() + "");
btDevice = null;
break;
}
break;
case MESSAGE_WRITE:
break;
case MESSAGE_READ:
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
connectedDeviceName = msg.getData().getString(DEVICE_NAME);
if(connectedDeviceName != null){
Toast.makeText(context, "Device: " + connectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case MESSAGE_TOAST:
Log.d(CLASS_TAG + "/" + "handler/toast", "Toast: " + msg.getData().getString(TOAST));
Toast.makeText(context, msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
public void onResume(){
super.onResume();
}
@Override
public void onDestroyView(){
super.onDestroyView();
}
@Override
public void onDetach(){
super.onDetach();
Log.d(CLASS_TAG, "in onDetach() !");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (resultCode == getActivity().RESULT_OK && DevicesList.EXTRA_DEVICE_ADDRESS != null) {
btDevice = btAdapter.getRemoteDevice(data.getExtras().getString(DevicesList.EXTRA_DEVICE_ADDRESS));
connectedDeviceAddress = data.getExtras().getString(DevicesList.EXTRA_DEVICE_ADDRESS);
if(connectedDeviceAddress != null){
btService.connect(btDevice);
}
Log.d(CLASS_TAG, "OnActivityResult: " + data.getExtras().getString(DevicesList.EXTRA_DEVICE_ADDRESS));
} else if (resultCode == -1){
Log.d(CLASS_TAG, "Bluetooth probably enabled");
}
}
/**
* Private method for checking if the bluetooth is on or off
*
* */
private void checkBluetoothState() {
if(btAdapter == null){
new AlertBox("Fatal error", "Bluetooth not supported. Aborting ", context);
}else{
if(btAdapter.isEnabled() != true){
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
/**
* Class for managing onClickListener for connection button
*/
class ConnectionClickListener implements View.OnClickListener{
@Override
public void onClick(View view) {
switch(tinyDB.getInt("connection_state")){
case BluetoothConnectionService.STATE_NONE:
if(btDevice == null){
Intent i = new Intent(getActivity(), DevicesList.class);
startActivityForResult(i, 1);
}
break;
case BluetoothConnectionService.STATE_CONNECTED:
if(btService != null){
btService.stop();
btDevice = null;
}
break;
}
}
}
}
<?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:layout_gravity="center_horizontal|top">
<LinearLayout
android:id="@+id/main_linlay1"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="120dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Status: "
android:id="@+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main_connect_txt" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connect"
android:id="@+id/main_connect_button"
style="@style/ButtonCheapRoomDuino"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next Scenery: "
android:id="@+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="None!"
android:id="@+id/main_scenery_txt" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Scenery"
android:id="@+id/main_scenery_button"
style="@style/ButtonCheapRoomDuino"/>
</LinearLayout>
</LinearLayout>
答案 0 :(得分:0)
我完成了它。我让我的应用程序像这样工作:
解雇我的应用后,我创建了HomeArag的MainActivity。在HomeFragment中,我有Button和TextView用于连接/显示BluetoothConnection的状态。
在HomeFragment中,我实现了Handler,用于从BluetoothService接收信息。收到消息后,我想更新TextView和Button文本。我在HomeFragment中使用获取TextView和Button的String参数的方法创建了公共接口。在onAttach(Activity a)中,我创建了mCallback对象来与活动进行交谈。
下一步是在MainActivity中实现此接口。从这个Activity我正在更新TextView和Button。一切都是这样的:
public interface ViewInterface{
public void onViewUpdate(String buttonTxt, String txtTxt);
}
@Override
public void onAttach(Activity a){
super.onAttach(a);
try{
mCallback = (ViewInterface)a;
}catch (ClassCastException e){
e.printStackTrace();
}
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(true) Log.i(CLASS_TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothConnectionService.STATE_CONNECTED:
threadTextString = "Connected to: " + connectedDeviceName;
threadBtnString = "Disconnect";
mCallback.onViewUpdate(threadBtnString, threadTextString);
break;
case BluetoothConnectionService.STATE_CONNECTING:
threadTextString = "Connecting...";
mCallback.onViewUpdate(threadBtnString, threadTextString);
break;
case BluetoothConnectionService.STATE_NONE:
threadBtnString = "Connect";
threadTextString = "You're not connectedd";
mCallback.onViewUpdate(threadBtnString, threadTextString);
break;
}
private void updateBtn(Button btn, String data){
btn.setText(data);
Log.d(CLASS_TAG + "/" + "updateBtn", "Data: " + data);
}
private void updateTxt(TextView txt, String data){
txt.setText(data);
Log.d(CLASS_TAG + "/" + "updateTxt", "Data: " + data);
}
public void update(String buttonTxt, String txtTxt){
this.updateTxt(connectTxt, txtTxt);
this.updateBtn(connectButton, buttonTxt);
}
@Override
public void onViewUpdate(String buttonTxt, String txtTxt) {
HomeFragment homeFragment = (HomeFragment)getSupportFragmentManager().findFragmentById(R.id.frame_container);
if(homeFragment != null){
homeFragment.update(buttonTxt, txtTxt);
}
}