2016-04-29 6 views
2

AndroidスタジオでNavigation Drawer Activityを起動したときに生成されるサンプルコードの作業中です。私がやろうとしているのは、含まれているビューをプログラマチックに変更することです。私の研究では、ViewStubがこれを行う最善の方法であることが示されています。しかし、私はそれを働かせることはできません。ViewStubが膨張しておらず、レイアウトが空白のままである - Android

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v4.widget.DrawerLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/drawer_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:openDrawer="start"> 

    <include 
     layout="@layout/app_bar_main" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <android.support.design.widget.NavigationView 
     android:id="@+id/nav_view" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_gravity="start" 
     android:fitsSystemWindows="true" 
     app:headerLayout="@layout/nav_header_main" 
     app:menu="@menu/activity_main_drawer" /> 

</android.support.v4.widget.DrawerLayout> 

app_bar_main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context="com.MY_APP.android.MainActivity"> 

    <android.support.design.widget.AppBarLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 

    </android.support.design.widget.AppBarLayout> 

    <ViewStub 
     android:id="@+id/main_content" 
     android:inflatedId="@id/main_content" 
     android:layout="@layout/content_main" 
     android:layout_height="match_parent" 
     android:layout_width="match_parent"/> 

    <android.support.design.widget.FloatingActionButton 
     android:id="@+id/fab" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="bottom|end" 
     android:layout_margin="@dimen/fab_margin" 
     android:src="@android:drawable/ic_dialog_email" /> 

</android.support.design.widget.CoordinatorLayout> 

content_main.xml:

問題の主なレイアウトのために関わる3つのファイルがあります
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:showIn="@layout/app_bar_main" 
    tools:context="com.MY_APP.android.MainActivity"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/content_textview" 
     android:text="//TODO Main Feed"/> 
</RelativeLayout> 

以下は私のMainActivity.javaです。何も起こっていないようで、content_mainは決して現れないようです。それは可視性の問題でしょうか?

package com.myapp.android; 


import android.app.Dialog; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.design.widget.NavigationView; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.MenuItem; 
import android.view.ViewStub; 
import android.widget.Toast; 

import com.facebook.FacebookSdk; 
import com.facebook.login.LoginManager; 
import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesUtil; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 

public class MainActivity 
     extends AppCompatActivity 
     implements NavigationView.OnNavigationItemSelectedListener { 


    NetworkHelpers NetworkHelper = new NetworkHelpers(); 
    SharedPreferences sharedpreferences; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

     //Check if user is connected 
     if(!NetworkHelper.checkConnectivity(this)){ 
      NetworkHelper.showNotConnectedAlert(this); 
     } 

     //Check for Google Play Services 
     checkGooglePlayServicesAvailable(); 

     //Get User Info From Database 
     sharedpreferences = getSharedPreferences("com.myapp.android.prefs", Context.MODE_PRIVATE); 
     String login_token = sharedpreferences.getString("login_token", ""); 
     String first_name = sharedpreferences.getString("first_name", ""); 
     String last_name = sharedpreferences.getString("last_name", ""); 
     String email = sharedpreferences.getString("email", ""); 


     if (login_token.isEmpty()){ 
      //Start LoginActivity 
      Intent intent = new Intent(this, LoginActivity.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
      finish(); 
      startActivity(intent); 
     }else{ 
      //Update user info 
      ArrayList<String> params = new ArrayList<String>(); 
      params.add(login_token); 
      new getUserInfo().execute(params); 
     } 

     //Create View 
     super.onCreate(savedInstanceState); 
     setContentView(com.myapp.android.R.layout.activity_main); 

     //Set Toolbar and Navigation Drawer 
     Toolbar toolbar = (Toolbar) findViewById(com.myapp.android.R.id.toolbar); 
     setSupportActionBar(toolbar); 
     DrawerLayout drawer = (DrawerLayout) findViewById(com.myapp.android.R.id.drawer_layout); 
     ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, com.myapp.android.R.string.navigation_drawer_open, com.myapp.android.R.string.navigation_drawer_close); 
     drawer.setDrawerListener(toggle); 
     toggle.syncState(); 
     NavigationView navigationView = (NavigationView) findViewById(com.myapp.android.R.id.nav_view); 
     navigationView.setNavigationItemSelectedListener(this); 

     ViewStub stub = (ViewStub) findViewById(R.id.main_content); 
     stub.setLayoutResource(R.layout.content_main); 
     stub.inflate(); 

    } 

    @Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(com.myapp.android.R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

    @SuppressWarnings("StatementWithEmptyBody") 
    @Override 
    public boolean onNavigationItemSelected(MenuItem item) { 
     int id = item.getItemId(); 

     if (id == R.id.nav_home) { 
      // Start Home Screen 
     } else if (id == R.id.nav_videos) { 
      // Start Videos Screen 
     } else if (id == R.id.nav_photos) { 
      // Start Photos Screen 
     } else if (id == R.id.nav_galleries) { 
      // Start Galleries Screen 
     } else if (id == R.id.nav_map) { 
      // Start Map Screen 
     } else if (id == com.myapp.android.R.id.nav_share) { 
      //Open share app dialog 
      Intent intent = new Intent(Intent.ACTION_SEND); 
      intent.setType("text/plain"); 
      intent.putExtra(Intent.EXTRA_SUBJECT, "My App"); 
      intent.putExtra(Intent.EXTRA_TEXT, "Check out My App: http://myapp.com/app"); 
      Intent chooser = Intent.createChooser(intent, "Tell a friend about My App"); 
      startActivity(chooser); 
     } else if (id == com.myapp.android.R.id.nav_logout){ 
      logout(); 
     } 

     DrawerLayout drawer = (DrawerLayout) findViewById(com.myapp.android.R.id.drawer_layout); 
     drawer.closeDrawer(GravityCompat.START); 
     return true; 
    } 

    //AsyncTask to get user info from api 
    class getUserInfo extends AsyncTask<ArrayList<String>, Void, String> { 
     @Override 
     protected String doInBackground(ArrayList<String>... params) { 
      String token = params[0].get(0); 
      String response = HttpRequest.post("http://api.myapp.com/users/get-info/").send("api_key=API_KEY&token="+token).body(); 
      return response; 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      try { 
       // Do JSON Stuff 
       JSONObject jsonobject = new JSONObject(result); 
       String status = jsonobject.get("status").toString(); 
       String message = jsonobject.get("message").toString(); 
       JSONObject userinfo = jsonobject.getJSONObject("user_info"); 

       //Set up user variables 
       String first_name = userinfo.get("first_name").toString(); 
       String last_name = userinfo.get("last_name").toString(); 
       String email = userinfo.get("email").toString(); 
       String display_name = userinfo.get("display_name").toString(); 
       String about = userinfo.get("about").toString(); 
       String newsletter = userinfo.get("newsletter").toString(); 


       if (status.equals("success")){ 
        updateSharedPreferences(first_name, last_name, email, display_name, about, newsletter); 
       }else if (status.equals("error")){ 
        logout(); 
       } else{ 
        logout(); 
       } 

      } catch (JSONException e) { 
       Toast.makeText(getApplicationContext(),"An unknown error occurred.", Toast.LENGTH_SHORT).show(); 
       logout(); 
      } 
     } 
    } 

    private boolean checkGooglePlayServicesAvailable() { 
     final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); 
     if (status == ConnectionResult.SUCCESS) { 
      return true; 
     } 

     if (GooglePlayServicesUtil.isUserRecoverableError(status)) { 
      final Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(status, this, 1); 
      if (errorDialog != null) 
      { 
       errorDialog.show(); 
      } 
     } 
     return false; 
    } 

    private void updateSharedPreferences(String first_name, String last_name, String email, String display_name, String about, String newsletter){ 
     //Put user info into sharedpreferences 
     SharedPreferences sharedpreferences = getSharedPreferences("com.myapp.android.prefs", Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = sharedpreferences.edit(); 
     editor.putString("first_name", first_name); 
     editor.putString("last_name", last_name); 
     editor.putString("email", email); 
     editor.putString("display_name", display_name); 
     editor.putString("about", about); 
     editor.putString("newsletter", newsletter); 
     editor.commit(); 
    } 

    private void logout(){ 
     //Logout of Facebook 
     FacebookSdk.sdkInitialize(this); 
     LoginManager.getInstance().logOut(); 

     //Unset shared preferences login token 
     SharedPreferences sharedpreferences = getSharedPreferences("com.myapp.android.prefs", Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = sharedpreferences.edit(); 
     editor.putString("login_token", ""); 
     editor.putString("facebook_token", ""); 
     editor.putString("google_token", ""); 
     editor.commit(); 

     //Open login screen 
     Intent intent = new Intent(getApplicationContext(), LoginActivity.class); 
     finish(); 
     startActivity(intent); 
    } 
} 
+0

onCreateView)それは良いはずです。 OnInflateListenerを追加して、それが膨張するのを確認しましたか? –

+0

私はsetContentView()の直後にそれを持っています。何が起こるかを知るためにリスナーを追加しようとします。 –

+0

後で読み込んだのはinflate()(リスナーが取得するもの)からの戻り値です。 –

答えて

0

私は同じ問題を抱えています。 StubViewを動的に膨張させるときには、別のxmlレイアウトを含めるために<include>タグを使用する場合とは動作が異なるようです。この場合、StubViewを置換するコンテンツは、拡張された後、AppBarレイアウトの下には配置されず、正確にその背後に配置されます。

この問題を解決する1つの方法は、StubViewをラップするようにRelativeLayoutを移動することです。だから、以下の変更が必要とされています

app_bar_main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context="com.MY_APP.android.MainActivity"> 

    <android.support.design.widget.AppBarLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 

    </android.support.design.widget.AppBarLayout> 

    <!-- Changed Content --> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:paddingLeft="@dimen/activity_horizontal_margin" 
     android:paddingRight="@dimen/activity_horizontal_margin" 
     android:paddingTop="@dimen/activity_vertical_margin" 
     android:paddingBottom="@dimen/activity_vertical_margin" 
     app:layout_behavior="@string/appbar_scrolling_view_behavior" 
     tools:showIn="@layout/app_bar_main" 
     tools:context="com.MY_APP.android.MainActivity"> 

     <ViewStub 
      android:id="@+id/main_content" 
      android:inflatedId="@id/main_content" 
      android:layout="@layout/content_main" 
      android:layout_height="match_parent" 
      android:layout_width="match_parent"/> 

    </RelativeLayout> 

    <!-- Changed Content --> 

    <android.support.design.widget.FloatingActionButton 
     android:id="@+id/fab" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="bottom|end" 
     android:layout_margin="@dimen/fab_margin" 
     android:src="@android:drawable/ic_dialog_email" /> 

</android.support.design.widget.CoordinatorLayout> 

content_main.xml:限り、あなたは例えば、中(setContentView後にそれをやったとして

<?xml version="1.0" encoding="utf-8"?> 
<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/content_textview" 
    android:text="//TODO Main Feed"/> 
関連する問題