I've set my application theme to be NoActionBar in AndroidManifest.xml because I only want a toolbar in my activity and a few fragments, so I'm willing to set it manually for those.
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
I made a view for my toolbar tb.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<TextView
android:id="#+id/tvTitle"
android:text="Main"
android:textColor="#color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:layout_gravity="center" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivBell"
android:background="#drawable/bell"
android:layout_gravity="right"
android:layout_marginRight="10dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true" />
</android.support.v7.widget.Toolbar>
and here's how I set it in the activity:
Toolbar toolbar = (Toolbar) getLayoutInflater().inflate(R.layout.main_toolbar, null);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
But it doesn't show up when I launch my app - any ideas what the problem could be?
Try below code:
In your style.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorAccent</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:splitMotionEvents">false</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
In your AndroidMenifest.xml
<application
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
In your Activity.java or BaseActivity.java file add following method and call it in onCreate or you can directly put method's code in Activity.java's onCreate:
public void setUpToolbar(String strTitle) {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
title = (TextView) toolbar.findViewById(R.id.tvTitle);
title.setText(strTitle);
}
}
Note: Don't forget to include tb.xml file in your activity's .xml file
In your Fragment.java or BaseFragment.java file add following method and call it in onCreateView or you can directly put method's code in Fragment.java's onCreateView:
public void setupToolBarWithBackArrow(Toolbar toolbar, #Nullable String Title) {
ActionBar actionBar;
// If you are using BaseActivity.java then keep below code as it is otherwise replace BaseActivity with Your Activity's name
((BaseActivity) getActivity()).setSupportActionBar(toolbar);
actionBar = ((BaseActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeAsUpIndicator(R.drawable.ic_back); // Set null if you don't want to show back arrow
}
// Remove this click listener if you set null in setHomeAsUpIndicator(...)
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mActivity.onBackPressed();
}
});
title = (TextView) toolbar.findViewById(R.id.title);
title.setText(Title != null ? Title : "");
}
Note: Don't forget to include tb.xml file in your fragment's .xml file
Related
Sorry for my bad English
I have an Android Kotlin Webview project splash screen with two theme
my project is working fine But I need To Splash Screen wait to Website Load Completely And The Hide
Here is My project codes:
MainActivity.kt :
class MainActivity : Activity() {
private var mWebView: WebView? = null
#SuppressLint("SetJavaScriptEnabled")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(R.style.Theme_Splash_kotlin_)
setContentView(R.layout.activity_main)
mWebView = findViewById(R.id.activity_main_webview)
val webSettings = mWebView?.getSettings()
if (webSettings != null) {
webSettings.javaScriptEnabled = true
}
mWebView?.setWebViewClient(MyWebViewClient())
// REMOTE RESOURCE
mWebView?.loadUrl("https://fa.azdamghest.com/")
// LOCAL RESOURCE
// mWebView.loadUrl("file:///android_asset/index.html");
}
override fun onBackPressed() {
if (mWebView!!.canGoBack()) {
mWebView!!.goBack()
} else {
super.onBackPressed()
}
}
}
MyWebViewClient.java :
class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String hostname;
// YOUR HOSTNAME
hostname = "fa.azdamghest.com";
Uri uri = Uri.parse(url);
if (url.startsWith("file:") || uri.getHost() != null && uri.getHost().endsWith(hostname)) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
activity_main.xml :
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
themes.xml :
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Splash_kotlin_" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">#color/purple_500</item>
<item name="colorPrimaryVariant">#color/purple_700</item>
<item name="colorOnPrimary">#color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/teal_200</item>
<item name="colorSecondaryVariant">#color/teal_700</item>
<item name="colorOnSecondary">#color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
<style name="splashScreenTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
<item name="android:windowBackground">#drawable/splash_image</item>
</style>
</resources>
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.splash_kotlin_">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/splashScreenTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Thank you Very much
Set the visiblity to invisible:
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible" />
Then put this underneath mWebView?.setWebViewClient(MyWebViewClient()):
mWebView.webViewClient = object: WebViewClient() {
var hasWebViewFinishedLoading: Boolean = false
override fun onPageFinished(viewEl: WebView?, urlStr: String) {
super.onPageFinished(viewEl, urlStr)
if (mWebView.progress >= 100 && !hasWebViewFinishedLoading) {
// Page finished loading.
hasWebViewFinishedLoading = true
// Hide the launch screen.
yourSplashScreenEl.visibility = INVISIBLE
// Show the webView.
mWebView.visibility = VISIBLE
}
}
}
So when the page finishes loading for the first time, it hides the splash screen.
This app has just two activities. MainActivity was renamed to SpecialsActivity. The other activity is PizzaActivity. Using the BottomNavigationView, I want to navigate between the two activities. So far, the app opens in SpecialsActivity, and the pizza button does open the PizzaActivity. But then it will not switch back to the SpecialsActivity. I think the issue is related to context. Please help.
SpecialsActivity.java
public class SpecialsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_specials);
Toolbar myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_specials:
Intent specials_intent = new Intent(this, SpecialsActivity.class);
startActivity(specials_intent);
return true;
case R.id.action_pizza:
Intent pizza_intent = new Intent(getApplicationContext(), PizzaActivity.class);
startActivity(pizza_intent);
return true;
default:
// Do nothing
}
return super.onOptionsItemSelected(item);
}
}
activity_specials.xml
<android.support.design.widget.BottomNavigationView
android:layout_width="0dp"
android:layout_height="49dp"
app:itemBackground="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_menu" />
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".SpecialsActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PizzaActivity"></activity>
</application>
bottom_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_specials"
android:icon="#drawable/ic_home_black_24dp"
android:title="Specials"
app:showAsAction="always"
android:onClick="onOptionsItemSelected" />
<item
android:id="#+id/action_pizza"
android:enabled="true"
android:icon="#drawable/ic_local_pizza_black_24dp"
android:title="Pizza"
app:showAsAction="always"
android:onClick="onOptionsItemSelected"/>
</menu>
Try changing
Intent pizza_intent = new Intent(getApplicationContext(), PizzaActivity.class);
into this
Intent pizza_intent = new Intent(this, PizzaActivity.class);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
Im trying to build a free book swap app for months. Got stuck in NavigationView code that points to a null object. I have extracted the full java for your persual. This is my very first call for help.
What i dont understand is, there is:
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this)
which is referenced to:
public class MainmainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
but the error message points to NullPointerException. as below:
java.lang.RuntimeException: Unable to start activity ComponentInfo{booksavenue.co.booksavenue/booksavenue.co.booksavenue.MainmainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
package booksavenue.co.booksavenue;
import android.support.annotation.NonNull;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;
public class MainmainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MessageFragment()).commit();
navigationView.setCheckedItem(R.id.nav_message);
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_message:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MessageFragment()).commit();
break;
case R.id.nav_chat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ChatFragment()).commit();
break;
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_send:
Toast.makeText(this, "Send", Toast.LENGTH_SHORT).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
initally i thought it is android:theme NoActionBar issue. but seems that it is not the case. Attaching the manifast file for your perusal too
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".SplashscreenActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<activity android:name=".forgetpassActivity" />
<activity android:name=".NewuserActivity" />
<activity android:name=".SecondActivity" />
<activity android:name=".TncActivity" />
<activity
android:name=".MainmainActivity"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
</application>
**
nav_header.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="176dp"
android:background="#color/colorAccent"
android:gravity="bottom"
android:orientation="vertical"
android:padding="16dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher_round" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:text="BooksAvenue"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="booksavenue#yahoo.com.sg" />
</LinearLayout>
Activity_mainmain.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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context="booksavenue.co.booksavenue.MainmainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu" />
</android.support.v4.widget.DrawerLayout>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
</resources>
I want to populate TextInputLayouts based on the item that a user selects from a Spinner. Below is my XML (the ID with "CreatePollAnswer" is the view I want to populate dynamically):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/create_poll_linearlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.troychuinard.fanpolls.Fragment.CreateFragment">
<FrameLayout
android:background="#drawable/image_border"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".525">
<Button
android:id="#+id/add_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Click to Add Image" />
</FrameLayout>
<LinearLayout
android:orientation="vertical"
android:padding="4dp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".475">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<EditText
android:id="#+id/create_poll_question_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:singleLine="true"
android:hint="#string/create_poll_question" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/how_many_answers_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/how_many_answers_text"
android:textColor="#color/black"
android:textSize="16sp" />
<Spinner
android:id="#+id/number_of_answers_spinner"
android:layout_width="wrap_content"
android:layout_gravity="bottom"
android:layout_height="24dp"
android:background="#android:drawable/btn_dropdown" />
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/create_poll_answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<EditText
android:id="#+id/create_poll_answer_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:singleLine="true"
/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
Code:
public class CreateFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private Button mAddImageButton;
private Spinner mSelectNumberofPollAnswers;
private String mSpinnerPosition;
private EditText mCreatePollQuestion;
private OnFragmentInteractionListener mListener;
private View mRootView;
private TextInputLayout mCreatePollAnswer;
private EditText mCreatePollAnswerEditText;
public CreateFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CreateFragment.
*/
// TODO: Rename and change types and number of parameters
public static CreateFragment newInstance(String param1, String param2) {
CreateFragment fragment = new CreateFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_create, container, false);
mAddImageButton = (Button) mRootView.findViewById(R.id.add_image_button);
mSelectNumberofPollAnswers = (Spinner) mRootView.findViewById(R.id.number_of_answers_spinner);
mCreatePollQuestion = (EditText) mRootView.findViewById(R.id.create_poll_question_editText);
mCreatePollAnswer = (TextInputLayout) mRootView.findViewById(R.id.create_poll_answer);
mCreatePollAnswerEditText = (EditText) mRootView.findViewById(R.id.create_poll_answer_editText);
// Inflate the layout for this fragment
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext(),
R.array.number_of_poll_answers, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mSelectNumberofPollAnswers.setAdapter(adapter);
mSelectNumberofPollAnswers.setOnItemSelectedListener(new YourItemSelectedListener());
return mRootView;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public class YourItemSelectedListener implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected = parent.getItemAtPosition(pos).toString();
Toast.makeText(getActivity().getApplicationContext(), selected, Toast.LENGTH_SHORT).show();
for (int i = 0; i < Integer.parseInt(selected); i++) {
ViewGroup layout = (ViewGroup) mRootView.findViewById(R.id.create_poll_linearlayout);
TextInputLayout newAnswer = new TextInputLayout(getActivity().getApplicationContext());
newAnswer = (TextInputLayout) mRootView.findViewById(R.id.create_poll_answer);
newAnswer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(newAnswer);
}
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
}
Here is the current error I am receiving:
java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:36)
at android.support.design.widget.TextInputLayout.<init>(TextInputLayout.java:139)
at android.support.design.widget.TextInputLayout.<init>(TextInputLayout.java:132)
at android.support.design.widget.TextInputLayout.<init>(TextInputLayout.java:128)
at com.troychuinard.fanpolls.Fragment.CreateFragment$YourItemSelectedListener.onItemSelected(CreateFragment.java:153)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:924)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:913)
at android.widget.AdapterView.access$300(AdapterView.java:51)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:883)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5527)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Styles:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowContentTransitions">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowSharedElementEnterTransition">#android:transition/move</item>
<item name="android:windowSharedElementExitTransition">#android:transition/move</item>
</style>
<style name="AppTheme.Dark" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">#color/primary_darker</item>
<item name="android:windowContentTransitions">true</item>
<item name="android:windowAllowEnterTransitionOverlap">true</item>
<item name="android:windowAllowReturnTransitionOverlap">true</item>
<item name="android:windowSharedElementEnterTransition">#android:transition/move</item>
<item name="android:windowSharedElementExitTransition">#android:transition/move</item>
<item name="colorPrimary">#color/primary</item>
<item name="colorPrimaryDark">#color/primary_dark</item>
<item name="colorAccent">#color/accent</item>
<item name="android:windowBackground">#color/primary</item>
<item name="colorControlNormal">#color/iron</item>
<item name="colorControlActivated">#color/white</item>
<item name="colorControlHighlight">#color/white</item>
<item name="android:textColorHint">#color/iron</item>
<item name="colorButtonNormal">#color/primary_darker</item>
<item name="android:colorButtonNormal">#color/primary_darker</item>
</style>
>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:textColorPrimary">#color/black</item>
<item name="android:textColorSecondary">#color/white</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">#android:color/black</item>
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="color">#android:color/white</item>
</style>
<style name="ToolBarStyle" parent="Theme.AppCompat">
<item name="android:titleTextColor">#android:color/white</item>
<item name="android:textColorPrimary">#android:color/white</item>
<item name="android:textColorSecondary">#android:color/white</item>
<item name="actionMenuTextColor">#android:color/white</item>
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
</style>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.troychuinard.fanpolls">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".FanPollsApplication"
android:allowBackup="true"
android:icon="#drawable/fan_polls_logo"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"> <!-- ADD THIS LINE -->
>
<activity
android:name=".SignupActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar"
android:windowSoftInputMode="stateHidden|adjustResize" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<meta-data
android:name="com.firebase.ui.GoogleClientId"
android:value="#string/google_client_id" />
<activity android:name="com.firebase.ui.auth.twitter.TwitterPromptActivity" />
<meta-data
android:name="com.firebase.ui.TwitterKey"
android:value="#string/twitter_app_key" />
<meta-data
android:name="com.firebase.ui.TwitterSecret"
android:value="#string/twitter_app_secret" />
<activity
android:name=".PollActivity"
android:label="#string/title_activity_poll"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".LoadingActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Discussion_Activity"
android:label="#string/title_activity_discussion_"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".HomeActivity" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".CreateActivity"
android:theme="#style/Theme.AppCompat.Light"
>
</activity>
</application>
In AndroidManifest.xml file add the following code inside the application tag
android:theme="#style/Theme.AppCompat.Light"
I want that whent the soft key board is open the activity page will scrolled.
To do this I added scroll View in xml,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.trying.MainActivity"
>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="#+id/LayoutBackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/background"
>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" >
<requestFocus />
</EditText>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
and changed the realativeLayout height in code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;
int x=getActionBarHeight();//in this line I get the actionBar height programicaly the function is in the end of page
RelativeLayout l= (RelativeLayout)findViewById(R.id.LayoutBackground);
l.getLayoutParams().height = (height-x);//the layout size = size of full screen - size of actionBar
}
//I saw this function in stackOverflow site. function to get the actionBar height
public int getActionBarHeight() {
TypedValue tv = new TypedValue();
getApplicationContext().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId);
return actionBarHeight;
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.trying"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:windowSoftInputMode="stateHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The idia is that the layout heigt is depended of screen size (all devices), and action bar heigt too.
My problem is that when I run the app, the background is small.
the it's It seems that the action bar size fell twice,
Add the following line of code to your manifest for the particular activity
android:windowSoftInputMode="adjustResize"
You don't need to add ScrollView in your layout. Remove it from xml. Then in AndroidManifest.xml, add the following lines in your activity:
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboardHidden"
android:windowSoftInputMode="adjustPan|stateAlwaysHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>