How can i access fragment layout in parent activity? - java

I have got a tabpager and fragments. And a frament has got a "GridView". I am using a basedapter innerclass in the fragment parent activity.
But when i want to set adapter to my gridview i m getting nullpointerexception. Because GridView variable is always null.how can solve this issue?
Fragment Parent MainActivity OnCreate Method;
GridView gv = (GridView)findViewById(R.id.gridview); // debugging and always null
gv.setAdapter(new AdapterB(this,WallPaperList));
Fragment xml
<!-- TODO: Update blank fragment layout -->
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
MyGrid.xml (For populate with adapter)
<?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:orientation="vertical">
<ImageView
android:id="#+id/imagepart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SeƧ"
android:id="#+id/checkBox" />
</LinearLayout>

You cant acces fragment views like that, becouse they could be not yet in the activity view hierarchy.
You have to add some method to your fragment, like
myCustomFragment.setGridAdapter(MyCustomGridViewAdapter adapter)
and in this method in your custom fragment:
public void setGridAdapter(){
this.myCustomGridAdapter = adapter;
GridView gv = (GridView)findViewById(R.id.gridview);
if(gv != null)
gv.setAdapter(this.myCustomGridAdapter);
}

This code:
GridView gv = (GridView)findViewById(R.id.gridview); // debugging and always null
gv.setAdapter(new AdapterB(this,WallPaperList));
should be inside of your fragment's onCreateView. You should create fragments that are independent from the activity they're attached to.
If you absolutely need to access the fragment's layout from your activity you need to delay the findViewById because the fragment's layout is not yet inflated when you call it:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
GridView gv = (GridView)findViewById(R.id.gridview);
gv.setAdapter(new AdapterB(this, WallPaperList));
}
}, 1000);
Although this code would work, I highly discourage you from using it!

Related

why might findViewById() crash relativeLayout init command?

I am writing a Chess app in Android Studio 3.0, and I want a PopupWindow to appear when the user clicks btnPopUpWindow, a button on the Chessboard layout. Here' the chessboard layout XML:
activity_chessboard.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="me.androidchess.MainActivity"
android:id="#+id/chessboardlayout">
<Button
android:id="#+id/popUpButton"
android:layout_width="172dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:text="Pop Up Menu"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginRight="8dp" />
</android.support.constraint.ConstraintLayout>
The XML layout above is loaded by Chessboard.java. Obviously, Chessboard would be the parent of the popup window, which is why I would want to use a RelativeLayout reference for the popup to see Chessboard.
Chessboard.java
public class Chessboard extends Activity {
Button btnPopUpWindow;
RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chessboard);
btnPopUpWindow = findViewById(R.id.popUpButton); // This works
relativeLayout = (RelativeLayout)findViewById(R.id.chessboardlayout); // <--- CRASHES HERE!!!
btnPopUpWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// https://www.youtube.com/watch?v=wxqgtEewdfo
gameTextArea.setText("Pop up Menu appears...");
}
});
}
Its that relativeLayout = (RelativeLayout)findViewById(R.id.chessboardlayout); line which crashes the app.
I am assuming that findViewById() is failing to locate the ID chessboardlayout, but I can't figure out why. I can't find the R.id directory in Android Studio, but I notice that chessboardlayout appears in the drop-down options when I type out the command. Plus I see the Id when I walk through the debugger. So I assume the Id has been properly filed.
But when I follow the debugger, the findViewById() call returns null, which can't be good. Specifically, an "Unable to start activity" exception is thrown by performLaunchActivity() in ActivityThread.java No idea how that is happening.
I've read through the other findViewById() threads that pop up in StackOverview searches, and a lot of those issues seem to revolve around the item returned by findViewById() not matching the local variable Button x = findViewById(R.id.TextFieldHere); for example. But that doesn't seem to be the case here... unless I don't understand how a RelativeLayout is supposed to work here...? Any advice/insight is appreciated, thank you.
Your R.id.chessboardlayout is an android.support.constraint.ConstraintLayout so you cannot cast it to RelativeLayout or it will cause ClassCastException.
So if you still want to use RelativeLayout as root of your layout, change your activity_chessboard.xml to this:
activity_chessboard.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context="me.androidchess.MainActivity"
android:id="#+id/chessboardlayout">
<Button
android:id="#+id/popUpButton"
android:layout_width="172dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:text="Pop Up Menu"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginRight="8dp" />
</RelativeLayout>
Then in your activity use the findViewById() normally.
setContentView(R.layout.activity_chessboard);
btnPopUpWindow = findViewById(R.id.popUpButton);
relativeLayout = (RelativeLayout)findViewById(R.id.chessboardlayout);

Change TextView on content_main.xml in MainActivity.java

I'm using the Android Studio standard template "Navigation Drawer Activity" which contains the content_main.xml layout.
On this layout is my textView which I want to change the text from my MainActivity.java.
I tried following but nothing changes:
LayoutInflater inflater = (LayoutInflater)this.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.content_main, null);
TextView txt = (TextView)view.findViewById(R.id.txt_head);
txt.setText("sdfsdf");
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/relativelayout_for_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.w4ter.ledcontroldesign.MainActivity"
tools:showIn="#layout/app_bar_main"
android:orientation="vertical"
android:paddingTop="10dp">
<TextView
android:text="Presets"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat.Headline"
android:id="#+id/txt_head" />
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#61000000" />
</LinearLayout>
there is no need of LayoutInflater. Simply use:
TextView textView = (TextView) findViewById(R.id.txt_head);
texView.setText("Hello");
Hope this helps.
You just need to access the TextView component the normal way. With that template the content_main.xml is included inside the main layout, so you sould do as follows in your main activity (maybe inside the onCreate method or wherever you need):
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = (TextView)view.findViewById(R.id.txt_head);
txt.setText("sdfsdf");
}
//...
}
Assuming that you have a app_bar_main.xml inside the main layout wich contains the content_main.xml. In the end everything is accessible from the main activity directly since the layouts are included in the main layout.
Hope it helps!

How do I hide or show layout elements when an Android Activity goes out of focus?

I am trying to hide certain elements in a layout when Android goes out of focus, such that when viewed in the "View recent applications" display, the layout elements will not be visible. Upon selecting the application and going into focus, these elements will be visible again.
My implementation below attempts to show the "content" layout when the application is in focus, and show the "overlay" layout when out of focus, via onWindowFocusChanged().
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is the content page"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/overlay"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is the overlay"/>
</RelativeLayout>
</FrameLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
FrameLayout layoutContainer;
RelativeLayout layoutContent;
RelativeLayout layoutOverlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutContainer = (FrameLayout) findViewById(R.id.container);
layoutContent = (RelativeLayout) findViewById(R.id.content);
layoutOverlay = (RelativeLayout) findViewById(R.id.overlay);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
layoutContent.setVisibility(View.VISIBLE);
layoutOverlay.setVisibility(View.GONE);
} else {
layoutOverlay.setVisibility(View.VISIBLE);
layoutContent.setVisibility(View.GONE);
}
}
}
enter code here
However, my implementation does not work. Anyone with any suggestion as to solve this? Thanks!
If you want to hide views in your layout in recent apps try like this
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,WindowManager.LayoutParams.FLAG_SECURE);

Getting Child from linear layout

I created layout file, consist of one linearlayout and two nested linearlayout inside the main one. When I using getParent method, it select the second nested linearlayout. My target was the first one nested linearlayout. So I gives the first nested linearlayout a ID called linear_top. Then I declared in the onCreateView, test and debug, I have no luck it shows that is null.
My target was AnimatedGifImageView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linear_top"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/music_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Love Story"
android:textAppearance="?android:attr/textAppearanceLarge" />
<com.music.flow.lib.AnimatedGifImageView
android:id="#+id/music_anim"
android:layout_width="match_parent"
android:layout_height="76dp"
android:scaleType="fitXY"
android:contentDescription="Animation"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RatingBar
android:id="#+id/music_rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="40dp"
android:numStars="4"
android:rating="3.5" />
<ImageView
android:id="#+id/btn_playmusic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:src="#drawable/resume" />
</LinearLayout>
OnCreateView
linearTop = (LinearLayout) v.findViewById(R.id.linear_top);
AnimatedGifImageView animatedGifImageView =
(AnimatedGifImageView) linearTop.getChildAt(1); /* Null Exception */
Child views are indexed from 0. In other words, the first child view is 0, the second child view is 1... and so on.
Also, why don't you just get the the ImageView by it's ID?
AnimatedGifImageView musicAnim = (AnimatedGifImageView) findViewById(R.id.music_anim);
#Override
public View onCreateView(View v, String name, Context context,
AttributeSet attrs) {
LinearLayout linearTop = (LinearLayout) v.findViewById(R.id.linear_top);
ImageView animatedGifImageView = (ImageView) linearTop.getChildAt(1); // NullPointer
return super.onCreateView(v, name, context, attrs);
}
Does your code look like this? You are getting a NullPointerException because in onCreateView, the parameter View v may be null, as mentioned in the docs here. Are you using fragments? If not, then don't use onCreateView. Place your code instead in onCreate like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearTop = (LinearLayout) findViewById(R.id.linear_top);
ImageView animatedGifImageView = (ImageView) linearTop.getChildAt(1);
setContentView(R.layout.activity_nested_linearlayout);
}
also, as what Sound Conception mentioned, you could just try to get the view directly by using its id instead of manually getting it using an index.

Custom ListView TextView Items all show gray bar at top

I'm having a problem with a custom ListView I am using in the ListActivity of my application. My problem is that all TextView items added to the ListView through an ArrayAdapter show up with a gray bar above them. I would include an image of the displayed ListView, but am unable since I do not have a reputation of 10 required by the stackoverflow site.
The layout file (index.xml) used to produce the ListView is defined as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical" >
<ListView
android:divider="#color/mg_red"
android:dividerHeight="1sp"
android:id="#android:id/list"
android:layout_height="fill_parent"
android:layout_width="fill_parent" />
<TextView
android:title="text_view"
android:background="#drawable/listitemback"
android:cacheColorHint="#drawable/listitemback"
android:id="#+id/listItem"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10sp"
android:textColor="#color/listitemtext"
android:textSize="16sp" />
</LinearLayout>
The ListActivity code used to display the list is as follows:
public class IndexListActivity extends ListActivity
{
private ListView m_listView = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
try
{
if (MGApplication.DEBUG_BUILD)
Log.i("TMG", "IndexListActivity.onCreate");
super.onCreate(savedInstanceState);
// Get our global data object.
MGApplication mgApp = (MGApplication) getApplication();
// Set view layout
SetContentView(R.layout.index);
// Get references to our ListView and AdView objects
m_listView = (ListView) findViewById(android.R.id.list);
// Create a new ArrayAdapter object that will be used to initialize
// the underlying ListView object.
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.index,
R.id.listItem,
mgApp.m_strAZRhymeNames);
// Assign array adapter
m_listView.setAdapter(aa);
}
catch (Exception e)
{
}
return;
}
}
Any help is greatly appreciated as I am at my wits end with this issue. I think I've tried every suggestion I could find on the web and I am unable to remove the gray bar.
Thank You,
Bob
you have to set this property in test.xml file with.
<ListView
android:id="#+id/listview_middle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="1dip"
android:layout_weight="1"
android:background="#ffffff"
android:cacheColorHint="#android:color/transparent"
android:choiceMode="singleChoice"
android:scrollingCache="false" />
and set some property in listview object.
lv.setVerticalFadingEdgeEnabled(false);
In my side that's work perfect.

Categories

Resources